package cn.regexp.websocket.mq;

import cn.regexp.websocket.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Regexpei
 * @date 2024/7/6 15:11
 * @description MQ 订单结果消息消费者
 */
@Component
@RocketMQMessageListener(consumerGroup = "MQOrderResultTopicListener", topic = MQConstant.ORDER_RESULT_TOPIC)
@Slf4j
public class MQOrderResultTopicListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("进入到订单结果消息消费者...");
        // 获取 token
        String token = orderMQResult.getToken();
        // 通过 token 获取 ws 服务对象
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        if (webSocketServer != null) {
            try {
                // 获取 session 并向客户端发信息
                webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
            } catch (IOException e) {
                log.error("发送消息失败...message: {}", e.getMessage(), e);
            }
        }
    }
}
